package com.balabala.filter;

import com.balabala.result.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * Created by zxd on 2023/4/25
 */
public class ResponseUtils {

    private  static  final ObjectMapper objectMapper=new ObjectMapper();

    /**
     * 返回数据转换
     * @param response
     * @return
     */
    public static Mono<Void> writeErrorInfo(ServerHttpResponse response, Result result) {

        try {
            response.getHeaders().set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
            response.getHeaders().set("Access-Control-Allow-Origin", "*");
            response.getHeaders().set("Cache-Control", "no-cache");
            String body = objectMapper.writeValueAsString(result);
            DataBuffer buffer = response.bufferFactory().wrap(body.getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Mono.just(buffer))
                    .doOnError(error -> DataBufferUtils.release(buffer));
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("json转换失败!");
        }
    }


}
